package com.cy.springcloudalibaba.services.impls;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.cy.springcloudalibaba.mappers.OrderMapper;
import com.cy.springcloudalibaba.models.Order;
import com.cy.springcloudalibaba.models.Product;
import com.cy.springcloudalibaba.services.AccountService;
import com.cy.springcloudalibaba.services.OrderService;
import com.cy.springcloudalibaba.services.ProductService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @Description: 订单
 * @ClassName: OrderServiceImpl
 * @Author: chenyu
 * @Date: 2025/2/6 10:22
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AccountService accountService;

    @Autowired
    private ProductService productService;

    @Override
    @DS(value="order-ds")
    @GlobalTransactional //seata全局事务注解
    public Integer createOrder(Integer userId, Integer productId) throws Exception {
        int amount = 1; //购买数量暂时设置为1

        log.info("[createOrder] 当前XID: {}", RootContext.getXID());

        //扣减库存
        Product product = productService.reduceStock(productId, amount);
        //扣减余额
        accountService.reduceBalance(userId, product.getPrice());

        Order order = new Order();
        order.setUserId(userId);
        order.setProductId(productId);
        order.setPayAmount(product.getPrice().multiply(new BigDecimal(amount)).longValue());

        orderMapper.insertSelective(order);
        log.info("[createOrder] 保存订单：{}", order.getId());

        return order.getId();
    }
}
